export const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

export const formatTheDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}

export const formatTheTime = date => {
  const hour = date.getHours()
  const minute = date.getMinutes()
  return [hour, minute].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

export const getRemainingDate = (startDate, endDate) => {
  var endDateTime = new Date(endDate).getTime()
  var startDateTime = new Date(startDate).getTime()
  var time = (endDateTime - startDateTime) / 1000   //计算相差秒数

  let day = timeFormin(parseInt(time / (60 * 60 * 24)))
  let hour = timeFormin(parseInt(time % (60 * 60 * 24) / 3600))
  let min = timeFormin(parseInt(time % (60 * 60 * 24) % 3600 / 60))
  return {
    day: formatNumber(day),
    hour: formatNumber(hour),
    min: formatNumber(min),
  }
}

export const countdownTime = (endDate) => {
  var nowDateTime = new Date().getTime()
  var endDateTime = new Date(endDate).getTime()
  var dateTime = (endDateTime - nowDateTime) / 1000
  // 获取 天 时  分 秒

  let day = parseInt(dateTime / (60 * 60 * 24))
  let hour = parseInt(dateTime % (60 * 60 * 24) / (60 * 60))
  let min = parseInt(dateTime % (60 * 60 * 24) % (60 * 60) / 60)
  let sec = parseInt(dateTime % (60 * 60 * 24) % (60 * 60) % 60)

  return {
    time: dateTime,
    day: timeFormat(day),
    hour: timeFormat(hour),
    min: timeFormat(min),
    sec: timeFormat(sec)
  }


}
const timeFormat = param => {
  if (param < 0) {
    param = 0
  }
  if (param < 10) {
    param = '0' + param
  }
  return param
}
const timeFormin = param => {
  return param < 0 ? 0 : param
}

export class Url {
  /**
    * 传入对象返回url参数
    * @param {Object} data {a:1}
    * @returns {string}
   */
  getParam(data) {
    let url = ''
    for (var key in data) {
      var value = data[key] !== undefined ? data[key] : ''
      url += `&${key}=${encodeURIComponent(value)}`
    }
    return url ? url.substring(1) : ''
  }
  getUrl(url, data) {
    // 判断原始url是否带有？
    // indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
    return url += (url.indexOf('?') < 0 ? '?' : '') + this.getParam(data)
  }
}

